package top.yokey.shopai.order.activity;

import android.view.View;
import android.widget.RelativeLayout;

import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.ArrayList;

import top.yokey.shopai.R;
import top.yokey.shopai.order.adapter.OrderDetailedGoodsAdapter;
import top.yokey.shopai.order.viewmodel.OrderDetailedVM;
import top.yokey.shopai.zcom.App;
import top.yokey.shopai.zcom.arouter.ARoutePath;
import top.yokey.shopai.zcom.base.BaseActivity;
import top.yokey.shopai.zcom.help.DialogHelp;
import top.yokey.shopai.zcom.help.ToastHelp;
import top.yokey.shopai.zcom.other.Constant;
import top.yokey.shopai.zcom.recycler.LineDecoration;
import top.yokey.shopai.zcom.util.JsonUtil;
import top.yokey.shopai.zcom.util.VerifyUtil;
import top.yokey.shopai.zsdk.ShopAISdk;
import top.yokey.shopai.zsdk.bean.OrderInfoBean;
import top.yokey.shopai.zsdk.data.GoodsData;
import top.yokey.shopai.zsdk.data.OrderPinGouData;
import top.yokey.shopai.zsdk.data.RetreatData;

@Route(path = ARoutePath.ORDER_DETAILED)
public class OrderDetailedActivity extends BaseActivity {

    private final ArrayList<OrderInfoBean.GoodsListBean> arrayList = new ArrayList<>();
    private final OrderDetailedGoodsAdapter adapter = new OrderDetailedGoodsAdapter(arrayList);
    @Autowired(name = Constant.DATA_ID)
    String orderId;
    private Toolbar mainToolbar = null;
    private AppCompatTextView toolbarTextView = null;
    private AppCompatTextView stateTextView = null;
    private AppCompatTextView stateTipsTextView = null;
    private AppCompatImageView stateImageView = null;
    private RelativeLayout logisticsRelativeLayout = null;
    private AppCompatTextView logisticsTextView = null;
    private AppCompatTextView logisticsTimeTextView = null;
    private AppCompatTextView addressNameTextView = null;
    private AppCompatTextView addressAreaTextView = null;
    private RelativeLayout messageRelativeLayout = null;
    private AppCompatTextView messageContentTextView = null;
    private RelativeLayout invoiceRelativeLayout = null;
    private AppCompatTextView invoiceContentTextView = null;
    private RelativeLayout paymentRelativeLayout = null;
    private AppCompatTextView paymentContentTextView = null;
    private AppCompatTextView nameTextView = null;
    private RecyclerView mainRecyclerView = null;
    private RelativeLayout zengRelativeLayout = null;
    private LinearLayoutCompat zengPinLinearLayout = null;
    private AppCompatTextView zengPinTextView = null;
    private AppCompatTextView discountsTextView = null;
    private AppCompatTextView shippingTextView = null;
    private AppCompatTextView priceTextView = null;
    private AppCompatTextView timeTextView = null;
    private AppCompatTextView customerTextView = null;
    private AppCompatTextView callTextView = null;
    private AppCompatTextView operaTextView = null;
    private OrderInfoBean bean = null;
    private OrderDetailedVM vm = null;

    @Override
    public void initView() {

        setContentView(R.layout.activity_order_detailed);
        mainToolbar = findViewById(R.id.mainToolbar);
        toolbarTextView = findViewById(R.id.toolbarTextView);
        stateTextView = findViewById(R.id.stateTextView);
        stateTipsTextView = findViewById(R.id.stateTipsTextView);
        stateImageView = findViewById(R.id.stateImageView);
        logisticsRelativeLayout = findViewById(R.id.logisticsRelativeLayout);
        logisticsTextView = findViewById(R.id.logisticsTextView);
        logisticsTimeTextView = findViewById(R.id.logisticsTimeTextView);
        addressNameTextView = findViewById(R.id.addressNameTextView);
        addressAreaTextView = findViewById(R.id.addressAreaTextView);
        messageRelativeLayout = findViewById(R.id.messageRelativeLayout);
        messageContentTextView = findViewById(R.id.messageContentTextView);
        invoiceRelativeLayout = findViewById(R.id.invoiceRelativeLayout);
        invoiceContentTextView = findViewById(R.id.invoiceContentTextView);
        paymentRelativeLayout = findViewById(R.id.paymentRelativeLayout);
        paymentContentTextView = findViewById(R.id.paymentContentTextView);
        nameTextView = findViewById(R.id.nameTextView);
        mainRecyclerView = findViewById(R.id.mainRecyclerView);
        zengRelativeLayout = findViewById(R.id.zengRelativeLayout);
        zengPinLinearLayout = findViewById(R.id.zengPinLinearLayout);
        zengPinTextView = findViewById(R.id.zengPinTextView);
        discountsTextView = findViewById(R.id.discountsTextView);
        shippingTextView = findViewById(R.id.shippingTextView);
        priceTextView = findViewById(R.id.priceTextView);
        timeTextView = findViewById(R.id.timeTextView);
        customerTextView = findViewById(R.id.customerTextView);
        callTextView = findViewById(R.id.callTextView);
        operaTextView = findViewById(R.id.operaTextView);

    }

    @Override
    public void initData() {

        if (VerifyUtil.isEmpty(orderId)) {
            ToastHelp.get().showDataError();
            onReturn(false);
            return;
        }
        setStateBarColor(R.color.yellow);
        setToolbar(mainToolbar, R.string.orderDetailed);
        observeKeyborad(R.id.mainLinearLayout);
        toolbarTextView.setTextColor(App.get().getColors(R.color.primary));
        mainToolbar.setBackgroundResource(R.drawable.selector_yellow);
        mainToolbar.setNavigationIcon(R.drawable.ic_action_back_primary);
        App.get().setRecyclerView(mainRecyclerView, adapter);
        mainRecyclerView.addItemDecoration(new LineDecoration(1, false));
        vm = getVM(OrderDetailedVM.class);

    }

    @Override
    public void initEvent() {

        logisticsRelativeLayout.setOnClickListener(view -> logistics());

        nameTextView.setOnClickListener(view -> App.get().startStore(bean.getStoreId()));

        adapter.setOnItemClickListener(new OrderDetailedGoodsAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position, OrderInfoBean.GoodsListBean bean) {
                App.get().startGoods(new GoodsData(bean.getGoodsId()));
            }

            @Override
            public void onRefund(int position, OrderInfoBean.GoodsListBean bean) {
                RetreatData data = new RetreatData();
                data.setOrderId(orderId);
                data.setOrderGoodsId(bean.getRecId());
                App.get().start(ARoutePath.RETREAT_REFUND, Constant.DATA_JSON, JsonUtil.toJson(data));
            }

            @Override
            public void onReturn(int position, OrderInfoBean.GoodsListBean bean) {
                RetreatData data = new RetreatData();
                data.setOrderId(orderId);
                data.setOrderGoodsId(bean.getRecId());
                App.get().start(ARoutePath.RETREAT_RETURN, Constant.DATA_JSON, JsonUtil.toJson(data));
            }
        });

        discountsTextView.setOnClickListener(view -> {
            StringBuilder discount = new StringBuilder();
            discount.append(String.format(getString(R.string.orderDetailedDiscounts), bean.getSale().size() + ""));
            for (int i = 0; i < bean.getSale().size(); i++) {
                for (int j = 0; j < bean.getSale().get(i).size(); j++) {
                    discount.append("\n").append(bean.getSale().get(i).get(j));
                }
            }
            DialogHelp.get().query(get(), getString(R.string.discounts), discount.toString(), null, null);
        });

        customerTextView.setOnClickListener(view -> App.get().startChat(ShopAISdk.get().getChatUrl(bean.getStoreMemberId(), "")));

        callTextView.setOnClickListener(view -> App.get().startCall(get(), bean.getStorePhone()));

        operaTextView.setOnClickListener(view -> {
            if (bean.getPinGouInfo() != null && bean.getStateDesc().equals("待发货")) {
                OrderPinGouData data = new OrderPinGouData();
                data.setPinGouId(bean.getPinGouInfo().getLogId());
                data.setBuyerId(bean.getPinGouInfo().getBuyerId());
                App.get().startOrderPinGou(data);
                return;
            }
            switch (bean.getStateDesc()) {
                case "已取消":
                    delete();
                    break;
                case "待付款":
                    cancel();
                    break;
                case "待发货":
                    refund();
                    break;
                case "待收货":
                    receive();
                    break;
                case "交易完成":
                    if (bean.isIfEvaluation()) {
                        evaluate();
                    } else {
                        delete();
                    }
                    break;
            }
        });

    }

    @Override
    public void initObserve() {

        vm.getInfoLiveData().observe(this, bean -> {
            arrayList.clear();
            OrderDetailedActivity.this.bean = bean;
            String time = String.format(getString(R.string.orderPaySn), bean.getOrderSn());
            stateTextView.setText(bean.getStateDesc());
            switch (bean.getStateDesc()) {
                case "已取消":
                    stateImageView.setImageResource(R.mipmap.ic_order_detailed_cancel);
                    stateTipsTextView.setText(R.string.addTime);
                    stateTipsTextView.append("：" + bean.getAddTime());
                    time = time + "\n" + getString(R.string.addTime) + "：" + bean.getAddTime();
                    operaTextView.setText(R.string.deleteOrder);
                    break;
                case "待付款":
                    stateImageView.setImageResource(R.mipmap.ic_order_detailed_wait_pay);
                    stateTipsTextView.setText(R.string.tipsOrderDetailedWaitPay);
                    operaTextView.setText(R.string.cancelOrder);
                    break;
                case "待发货":
                    stateImageView.setImageResource(R.mipmap.ic_order_detailed_wait_deliver);
                    stateTipsTextView.setText(R.string.payTime);
                    stateTipsTextView.append("：" + (bean.getPaymentName().equals("online") ? bean.getPaymentTime() : bean.getAddTime()));
                    time = time + "\n" + getString(R.string.addTime) + "：" + bean.getAddTime();
                    time = time + "\n" + getString(R.string.payTime) + "：" + (bean.getPaymentName().equals("online") ? bean.getPaymentTime() : bean.getAddTime());
                    if (bean.isIfLock()) {
                        stateTextView.setText(R.string.refundReturnIng);
                        operaTextView.setVisibility(View.GONE);
                    } else {
                        operaTextView.setText(R.string.applyRefund);
                        operaTextView.setVisibility(View.VISIBLE);
                    }
                    break;
                case "待收货":
                    stateImageView.setImageResource(R.mipmap.ic_order_detailed_wait_receive);
                    stateTipsTextView.setText(R.string.deliverTime);
                    stateTipsTextView.append("：" + bean.getShippingTime());
                    time = time + "\n" + getString(R.string.addTime) + "：" + bean.getAddTime();
                    time = time + "\n" + getString(R.string.payTime) + "：" + (bean.getPaymentName().equals("online") ? bean.getPaymentTime() : bean.getAddTime());
                    time = time + "\n" + getString(R.string.deliverTime) + "：" + bean.getShippingTime();
                    operaTextView.setText(R.string.confirmReceive);
                    break;
                case "交易完成":
                    stateImageView.setImageResource(R.mipmap.ic_order_detailed_finish);
                    stateTipsTextView.setText(R.string.deliverTime);
                    stateTipsTextView.append("：" + bean.getShippingTime());
                    time = time + "\n" + getString(R.string.addTime) + "：" + bean.getAddTime();
                    time = time + "\n" + getString(R.string.payTime) + "：" + (bean.getPaymentName().equals("online") ? bean.getPaymentTime() : bean.getAddTime());
                    time = time + "\n" + getString(R.string.deliverTime) + "：" + bean.getShippingTime();
                    time = time + "\n" + getString(R.string.finishTime) + "：" + bean.getFinnshedTime();
                    if (bean.isIfEvaluation()) {
                        operaTextView.setText(R.string.orderEvaluate);
                    } else {
                        operaTextView.setText(R.string.deleteOrder);
                    }
                    break;
            }
            if (bean.getPinGouInfo() != null && bean.getStateDesc().equals("待发货")) {
                operaTextView.setText(R.string.pinGouDetail);
            }
            addressNameTextView.setText(String.format(getString(R.string.goodsBuyReceiveName), bean.getReciverName()));
            addressNameTextView.append(" " + bean.getReciverPhone());
            addressAreaTextView.setText(bean.getReciverAddr());
            if (!VerifyUtil.isEmpty(bean.getOrderMessage())) {
                messageRelativeLayout.setVisibility(View.VISIBLE);
                messageContentTextView.setText(bean.getOrderMessage());
            } else {
                messageRelativeLayout.setVisibility(View.GONE);
            }
            if (!VerifyUtil.isEmpty(bean.getInvoice())) {
                invoiceRelativeLayout.setVisibility(View.VISIBLE);
                invoiceContentTextView.setText(bean.getInvoice());
            } else {
                invoiceRelativeLayout.setVisibility(View.GONE);
            }
            if (!VerifyUtil.isEmpty(bean.getPaymentName())) {
                paymentRelativeLayout.setVisibility(View.VISIBLE);
                paymentContentTextView.setText(bean.getPaymentName());
            } else {
                paymentRelativeLayout.setVisibility(View.GONE);
            }
            nameTextView.setText(bean.getStoreName());
            arrayList.addAll(bean.getGoodsList());
            adapter.notifyDataSetChanged();
            if (bean.getZengpinList().size() == 0) {
                zengRelativeLayout.setVisibility(View.GONE);
                zengPinLinearLayout.setVisibility(View.GONE);
            } else {
                zengRelativeLayout.setVisibility(View.VISIBLE);
                zengPinLinearLayout.setVisibility(View.VISIBLE);
                zengPinTextView.setText(bean.getZengpinList().get(0).getGoodsName());
                zengPinTextView.append(" x" + bean.getZengpinList().get(0).getGoodsNum());
            }
            discountsTextView.setText(String.format(getString(R.string.orderDetailedDiscounts), bean.getSale().size() + ""));
            shippingTextView.setText("￥");
            shippingTextView.append(bean.getShippingFee());
            priceTextView.setText("￥");
            priceTextView.append(bean.getRealPayAmount());
            timeTextView.setText(time);
        });

        vm.getCurrentLiveData().observe(this, string -> {
            String info = JsonUtil.getString(string, "deliver_info");
            logisticsTextView.setText(JsonUtil.getString(info, "context"));
            logisticsTimeTextView.setText(JsonUtil.getString(info, "time"));
            logisticsRelativeLayout.setVisibility(View.VISIBLE);
        });

        vm.getCancelLiveData().observe(this, string -> {
            ToastHelp.get().showSuccess();
            vm.getInfo(orderId);
            LiveEventBus.get(Constant.DATA_REFRESH).post(true);
        });

        vm.getDeleteLiveData().observe(this, string -> {
            ToastHelp.get().showSuccess();
            vm.getInfo(orderId);
            LiveEventBus.get(Constant.DATA_REFRESH).post(true);
            onReturn(false);
        });

        vm.getReceiveLiveData().observe(this, string -> {
            ToastHelp.get().showSuccess();
            vm.getInfo(orderId);
            LiveEventBus.get(Constant.DATA_REFRESH).post(true);
        });

        vm.getErrorLiveData().observe(this, bean -> {
            if (bean.getCode() == 1) {
                DialogHelp.get().query(get(), R.string.loadFailure, bean.getReason(), view -> onReturn(false), view -> vm.getInfo(orderId));
                return;
            }
            if (bean.getCode() == 2) {
                logisticsRelativeLayout.setVisibility(View.GONE);
                return;
            }
            ToastHelp.get().show(bean.getReason());
        });

    }

    @Override
    public void onResume() {

        super.onResume();
        vm.getInfo(orderId);
        vm.getCurrent(orderId);

    }

    //自定义方法

    private void delete() {

        DialogHelp.get().query(get(), R.string.confirmSelection, R.string.deleteOrder, null, view -> vm.deleteOrder(orderId));

    }

    private void cancel() {

        DialogHelp.get().query(get(), R.string.confirmSelection, R.string.cancelOrder, null, view -> vm.cancelOrder(orderId));

    }

    private void receive() {

        DialogHelp.get().query(get(), R.string.confirmSelection, R.string.confirmReceive, null, view -> vm.receiveOrder(orderId));

    }

    private void logistics() {

        App.get().start(ARoutePath.ORDER_LOGISTICS, Constant.DATA_ID, orderId);

    }

    private void refund() {

        RetreatData data = new RetreatData();
        data.setOrderId(orderId);
        App.get().start(ARoutePath.RETREAT_REFUND_ALL, Constant.DATA_JSON, JsonUtil.toJson(data));

    }

    private void evaluate() {

        App.get().start(ARoutePath.ORDER_EVALUATE, Constant.DATA_ID, orderId);

    }

}
